<?php
$db = Database::getDatabase();

// Start with boring standard values. These are mainly just today's dates.
$ViewEvent = 1;
$ViewTimeMode = 'week';
$ViewOutput = 'both';
$ViewDay = date('j');
$ViewMonth = date('n');
$ViewYear = date('Y');

// Get the available events in the database.
$Events = GetEvents();
$EventIDs = array_keys($Events);
$EventNames = array_values($Events);

// Fill out our values if the form was submitted.
if (isset($_POST['SubmitButton']) && $_POST['SubmitButton']) {
    $ViewEvent = SanitizeWhiteList($_POST['ViewEvent'], $EventIDs, $EventIDs[0]);
    $ViewOutput = SanitizeWhiteList($_POST['ViewOutput'], array('both', 'graph', 'table'), 'both');
    $ViewTimeMode = SanitizeWhiteList($_POST['ViewTimeMode'], array('week', 'month', 'year'), 'week');

    $ViewDay = SanitizeWhiteList($_POST['ViewDay'], range(1, 31), date('j'));
    $ViewMonth = SanitizeWhiteList($_POST['ViewMonth'], range(1, 12), date('n'));
    $ViewYear = SanitizeWhiteList($_POST['ViewYear'], range(2010, 2012), date('Y'));
}
// This is the GET query string that is passed to chart.php, which will handle the actual (chart) data manipulation and displaying.
$ChartParameters = "?ViewEvent=$ViewEvent&ViewTimeMode=$ViewTimeMode&ViewDay=$ViewDay&ViewMonth=$ViewMonth&ViewYear=$ViewYear";

// Now is time to fetch table data, me thinks.
if ($ViewOutput == 'table' || $ViewOutput == 'both') {
    $MonthArray = array();
    for ($i = 1; $i < 13; $i++) {
        $MonthArray[] = date("F", mktime(0, 0, 0, $i, 1));
    }
    $TableHead = "<tr><th colspan=\"4\">" . $EventNames[($ViewEvent - 1)] . " (" . ucfirst($ViewTimeMode) . " of " . $MonthArray[($ViewMonth - 1)] . " $ViewDay, $ViewYear)</th></tr>";
    $TableBody = '';

    if ($ViewTimeMode == 'week') {
        $StartingDate = FormatDate($ViewDay, $ViewMonth, $ViewYear);
        // I hope that PHP is smart enough to just switch the month over in the case of an overflow.
        $EndingDate = FormatDate(($ViewDay + 7), $ViewMonth, $ViewYear);
        $Query = "SELECT EventType.Type_Name, COUNT(Event.Event_ID) AS EventCount, CONVERT(Date_Event, DATE) AS EventDate FROM The_Event AS Event LEFT JOIN Event_Type AS EventType ON EventType.Type_ID = Event.Type_ID WHERE Event.Type_ID = $ViewEvent AND Event.Date_Event BETWEEN '$StartingDate'AND '$EndingDate' GROUP BY EventDate ORDER BY EventDate ASC";
    } else if ($ViewTimeMode == 'month') {
        $StartingDate = FormatDate(1, $ViewMonth, $ViewYear);
        // This will fetch the last day of the given month. (Hopefully correctly).
        $EndingDate = FormatDate(date('t', mktime(0, 0, 0, $ViewMonth, 1, $ViewYear)), $ViewMonth, $ViewYear);
    } else if ($ViewTimeMode == 'year') {
        $StartingDate = FormatDate(1, 1, $ViewYear);
        // This will fetch the last day of the given month. (Hopefully correctly).
        $EndingDate = FormatDate(31, 12, $ViewYear);
    }

    $Query = "SELECT EventType.Type_Name, COUNT(Event.Event_ID) AS EventCount, CONVERT(Date_Event, DATE) AS EventDate FROM The_Event AS Event LEFT JOIN Event_Type AS EventType ON EventType.Type_ID = Event.Type_ID WHERE Event.Type_ID = $ViewEvent AND Event.Date_Event BETWEEN '$StartingDate'AND '$EndingDate' GROUP BY EventDate ORDER BY EventDate ASC";
    $Result = $db->query($Query);
    if ($db->hasRows($Result)) {
        $Rows = $db->getRows($Result);
        $i = 1;
        $TableHead .= '<tr><th>Entry Number</th><th>Event Name</th><th>Occurance rate</th><th>Occurance date</th></tr>';
        foreach ($Rows as $Row) {
            $TableBody .= '<tr><td>#' . $i++ . '</td><td>' . $Row['Type_Name'] . '</td><td>' . $Row['EventCount'] . '</td><td>' . $Row['EventDate'] . '</td></tr>';
        }
    } else {
        $TableBody = '<tr col="3"><td>No data was retrieved.</td></tr>';
    }
}
?>
<div style="margin: 20px">
    <h2>Event Statistics</h2>
    <span>You can view any event over a period of time such as a day, week, month or year.</span><br />
    <br />
    <div id="statspanel">
        <h4>Event Statistics</h4>
        <form action="./view_stats.php?do=events" method="post">
            <label for="ViewEvent">Event: </label>
            <select id="ViewEvent" name="ViewEvent"><?php echo GenerateSelect($EventIDs, $EventNames); ?></select><br />
            <label for="ViewOutput">Output as: </label>
            <select id="ViewOutput" name="ViewOutput"><option value="both">Table and Graph</option><option value="graph">Graph Only</option><option value="table">Table Only</option></select><br />
            <br />
            <h4>Time View</h4>
            <label for="ViewTimeMode">Time Period: </label>
            <select id="ViewTimeMode" name="ViewTimeMode"><option selected="selected" value="week">Week</option><option value="month">Month</option><option value="year">Year</option></select><br />
            <span>Starting date: </span>
            <select id="ViewDay" name="ViewDay"><?php echo GenerateSelect(range(1, 31), range(1, 31), (!is_null($ViewDay) ? ($ViewDay - 1) : (date("j") - 1))); ?></select>
            <select id="ViewMonth" name="ViewMonth"><?php echo GenerateMonthSelect($ViewMonth); ?></select>
            <select id="ViewYear" name="ViewYear"><?php echo GenerateSelect(range(2010, 2012), range(2010, 2012), 1); ?></select>
            <br />
            <input type="submit" name="SubmitButton" value="View" />
            <input type="reset" name="ResetButton" value="Reset" />
        </form>
    </div>
    <div style="text-align: center">
        <br />
        <?php
        if ($ViewOutput == 'graph' || $ViewOutput == 'both') {
            echo "<img src=\"chart.php$ChartParameters\" height=\"300\" width=\"600\" alt=\"chat\" title=\"chart\"/>";
        }
        ?>
    </div>
    <br />
    <table class="resulttable">
        <?php
        echo $TableHead;
        echo $TableBody;
        ?>
    </table>
</div>